package com.mc.fastkit.ext

import androidx.viewpager2.widget.ViewPager2

fun ViewPager2.doOnPageSelected(callback: (position: Int) -> Unit): ViewPager2.OnPageChangeCallback {
    return addPageCallback(onPageSelected = callback)
}

fun ViewPager2.doOnPageScrolled(
    callback: (
        position: Int,
        positionOffset: Float,
        positionOffsetPixels: Int,
    ) -> Unit,
): ViewPager2.OnPageChangeCallback {
    return addPageCallback(onPageScrolled = callback)
}

fun ViewPager2.doOnScrollStateChanged(callback: (state: Int) -> Unit): ViewPager2.OnPageChangeCallback {
    return addPageCallback(onPageScrollStateChanged = callback)
}

inline fun ViewPager2.addPageCallback(
    crossinline onPageScrolled: (
        position: Int,
        positionOffset: Float,
        positionOffsetPixels: Int,
    ) -> Unit = { _, _, _ -> },
    crossinline onPageSelected: (position: Int) -> Unit = {},
    crossinline onPageScrollStateChanged: (state: Int) -> Unit = {},
): ViewPager2.OnPageChangeCallback {
    val listener = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int,
        ) = onPageScrolled(position, positionOffset, positionOffsetPixels)

        override fun onPageSelected(position: Int) = onPageSelected(position)
        override fun onPageScrollStateChanged(state: Int) = onPageScrollStateChanged(state)
    }
    registerOnPageChangeCallback(listener)
    return listener
}